package com.jiuzhi.app.common.wxutil.model;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * User: jason
 * Date: 14-5-23 下午3:44
 */
public class HttpUtils {

    /**
     * 增加一个cookie
     * @param response  jsp响应对象
     * @param cookieName cookie名字
     * @param cookieValue cookie值
     * @param maxAge cookie生命周期  以秒为单位, 若为0，则永不过期
     */
    public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, int maxAge) {
        Cookie cookie = new Cookie(cookieName,cookieValue);
        cookie.setPath("/");
        if(maxAge>0)  cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private static Map<String,Cookie> getCookies(HttpServletRequest request){
        Map<String,Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    /**
     * 根据cookie名称获取其值
     * @param request
     * @param name
     * @return
     */
    public static String getCookieByName(HttpServletRequest request, String name){
        Map<String,Cookie> cookieMap = getCookies(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie.getValue();
        }else{
            return null;
        }
    }

    public static String postUrlWithCustomHeaders(String url,Map<String,String> headers,String postData){
        InputStream is = null;
        BufferedReader br = null;
        InputStreamReader isr = null;
        OutputStreamWriter wr = null;
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            //增加headers
            if(headers != null && headers.size()>0){
                for(Map.Entry<String,String> entry : headers.entrySet()){
                    conn.addRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            /*conn.addRequestProperty("X-AVOSCloud-Application-Id", "rvzn0nipzoiguzby5j56mflfl9y0oiz2b68wq9y38xwmqlz7");
            conn.addRequestProperty("X-AVOSCloud-Application-Key", "luf3kdaz3jbzgu66ifvn4pzmerz6yhrz35y97vkimvuk0idx");
            conn.addRequestProperty("Content-Type", "application/json");*/
            conn.setDoInput(true);
            conn.setDoOutput(true);
            if(StringUtils.isNotEmpty(postData)) {
                wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                wr.write(postData);
                wr.flush();
            }
            is = conn.getInputStream();//拿到输入流
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            return br.readLine();
        }catch (Exception e){
            e.printStackTrace();
            return "err";
        }finally {
            try{
                if(br!=null){
                    br.close();
                }
                if(isr!=null){
                    isr.close();
                }
                if(is!=null){
                    is.close();
                }
            }catch (Exception ignored){}
        }
    }


    public static String invokeHttpGetUrl(String url){
        InputStream is = null;
        BufferedReader br = null;
        InputStreamReader isr = null;
        try{
            URL u = new URL(url);
            HttpURLConnection urlConnection = (HttpURLConnection)u.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Accept-Charset","utf-8");
            urlConnection.connect();
            is = urlConnection.getInputStream();//拿到输入流
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            return br.readLine();
        }catch (Exception e){
            throw new RuntimeException(url+"连接失败！");
        }finally {
            try{
                if(br!=null){
                    br.close();
                }
                if(isr!=null){
                    isr.close();
                }
                if(is!=null){
                    is.close();
                }
            }catch (Exception ignored){}
        }
    }
}
